/*
 * Copyright (C) 2012 VinaVAC. All rights reserved.
 */
package org.vinavac.mob.mbean;

import java.io.Serializable;
import java.util.List;
import javax.faces.model.SelectItem;
import org.vinavac.bean.AbstractSessionBean;
import org.vinavac.mob.util.JsfUtil;

/**
 *
 * @author Quang <quangtin3@gmail.com>
 */
public abstract class AbstractMobileBean<T> implements Serializable {

    protected static final String MOBILE_VIEW_MAIN = "pm:main";
    protected static final String MOBILE_VIEW_NEW = "pm:new";
    protected static final String MOBILE_VIEW_EDIT = "pm:edit";
    protected T selected;

    public AbstractMobileBean() {
    }

    protected abstract AbstractSessionBean<T> getSessionBean();

    protected abstract T emptyEntity();

    public T getSelected() {
        if (selected == null) {
            selected = emptyEntity();
        }
        return selected;
    }

    public void setSelected(T current) {
        this.selected = current;
    }

    public String prepareCreate() {
        selected = emptyEntity();
        return MOBILE_VIEW_NEW;
    }

    public String create() {
        getSessionBean().create(selected);
        return MOBILE_VIEW_MAIN;
    }

    public String update() {
        getSessionBean().edit(selected);
        return MOBILE_VIEW_MAIN;
    }

    public String destroy() {
        getSessionBean().remove(selected);
        selected = null;
        return MOBILE_VIEW_MAIN;
    }

    public T find(Integer key) {
        return getSessionBean().find(key);
    }

    public List<T> getItems() {
        return getSessionBean().findAll();
    }

    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(getSessionBean().findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(getSessionBean().findAll(), true);
    }

    public SelectItem[] getItemsAvailableSelectOneRadio() {
        return JsfUtil.getSelectItems(getSessionBean().findAll(), false);
    }
}
